package com.memexue.order.controller;

import com.memexue.common.ProductInfoOutput;
import com.memexue.core.vo.ResultVo;
import com.memexue.order.converter.OrderForm2OrderDtoConverter;
import com.memexue.order.dto.OrderDto;
import com.memexue.order.enums.OrderResultEnum;
import com.memexue.order.form.OrderForm;
import com.memexue.order.service.OrderService;
import com.memexue.product.client.ProductClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductClient productClient;

    @GetMapping("getProductMsg")
    public String getProductMsg(){
        String response = productClient.productMsg();
        log.info("product res={}", response);
        return response;
    }
    /**
     * 1. 参数校验
     * 2. 查询商品信息（调商品服务）
     * 3. 计算总价
     * 4. 扣库存（调用商品服务）
     * 5. 订单入库
     */
    @PostMapping("create")
    public ResultVo<Map<String, String>> create(@Valid @RequestBody OrderForm orderForm,
                                                BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("订单创建参数错误。orderForm={}", orderForm);
            return ResultVo.failure(OrderResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        OrderDto orderDto = null;
        try {
            orderDto = OrderForm2OrderDtoConverter.covert(orderForm);
        } catch (Exception e) {
            log.error("订单信息存在错误", e);
            return ResultVo.failure(OrderResultEnum.PARAM_ERROR.getCode(),
                    OrderResultEnum.PARAM_ERROR.getMsg());
        }
        if(CollectionUtils.isEmpty(orderDto.getOrderDetailList())){
            log.warn("创建订单购物车信息为空");
            return ResultVo.failure(OrderResultEnum.CART_EMPTY.getCode(),
                    OrderResultEnum.CART_EMPTY.getMsg());
        }
        OrderDto result = orderService.create(orderDto);
        Map<String, String> map = new HashMap<>();
        map.put("orderId", result.getOrderId());
        return ResultVo.success(map);
    }
    @GetMapping("/getTest")
    public Object getTEst(){
        List<ProductInfoOutput> productInfoList = productClient.listForOrder(Arrays.asList("164103465734242707"));
        return productInfoList;
    }
}
